/**
 * 
 */
package com.and.xmppsdk;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.drl.xmpp.Contact;
import org.drl.xmpp.TChat;
import org.drl.xmpp.TChatManager;
import org.drl.xmpp.TMessage;
import org.drl.xmpp.TSession;
import org.drl.xmpp.TalkClient;
import org.drl.xmpp.UserInfo;
import org.drl.xmpp.storage.AbstractTable;
import org.drl.xmpp.storage.DataBaseManager;
import org.drl.xmpp.storage.TableChageListener;
import org.drl.xmpp.storage.table.MessageTable;
import org.drl.xmpp.storage.table.SessionTable;
import org.drl.xmpp.util.StringHelper;
import org.drl.xmpp.util.StringUtils2;
import org.jivesoftware.smack.packet.Message;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.and.xmppsdk.adapter.MessageAdapter;
import com.and.xmppsdk.util.ChatHideInput;

/**
 * 聊天页面,发送聊天信息，显示聊天信息.
 * 
 * @author hljdrl@gmail.com
 * 
 * 
 */
public class ChatActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, OnItemClickListener ,TableChageListener{

	private Button mBtnStrangeToContact;

	private TextView mStrangeToContact;

	/**
	 * 会话列表ListView
	 */
	private ListView mConverList;

	/**
	 * 表情按钮
	 */
	private ImageView mBtnFace;

	/**
	 * 文字输入框
	 */
	private EditText mInput;

	/**
	 * 发送按钮
	 */
	private Button mBtnSend;

	/**
	 * 选择图片
	 */
	private LinearLayout mBtnImage;

	/**
	 * 语音按钮
	 */
	private LinearLayout mBtnAudio;

	// /**
	// * 录音时出现的框
	// */
	// private ChatRecordPopWindow mRecordWindow;

	/**
	 * 视频按钮
	 */
	private LinearLayout mBtnVideo;

	/**
	 * 表情布局
	 */
	private LinearLayout mFaceLayout;

	private GridView mFaceGridView;

	/**
	 * 107个表情
	 */
	private int[] imageIds = new int[107];

	Contact mContact;
	TalkClient talk;
	private UserInfo mUserInfo;
	private TChat mTChat;
	private TChatManager mTChatManager;
	private Cursor mCursor ;
	private MessageAdapter messageAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.root_aty_chat);
		talk = XmppApplication.getXmppSDK(this);
		mTChatManager = talk.getChatManager();
		DataBaseManager.addTableChageListener(this);
		mUserInfo = talk.getUserInfo();
		mContact = getIntent().getExtras().getParcelable("contact");
		if (mContact != null) {
			mTitleHelper.setTitle(mContact.getName());
		} else {
			mTitleHelper.setTitle("对话");
		}
		setup();
		TextView title = (TextView) findViewById(R.id.actionbar_title);
		title.setText(StringUtils2.parseName(mContact.getJID()));
		saveSessionChat();
		setupTChat();
	}
	@Override
	protected void onReleaseMemory() {
		
	}
	private void setupTChat()
	{
		mTChat =  mTChatManager.getChat(mContact);
		if(mTChat==null){
			mTChat = mTChatManager.createChat(mContact, null);
		}
		if(mTChat!=null){
			mTChat.setOpen(true);
		}
		MessageTable table = MessageTable.getInstance();
		mCursor = table.readChatMessages(mUserInfo, mContact);
		startManagingCursor(mCursor);
		messageAdapter = new MessageAdapter(this, mCursor,mUserInfo,mContact);
		mConverList.setAdapter(messageAdapter);
		mConverList.setStackFromBottom(true); 
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mTChat!=null){
			mTChat.setOpen(false);
		}
		DataBaseManager.removeTableChageListener(this);
	}

	private TSession mSessionItem;

	private void saveSessionChat() {

		mSessionItem =getIntent().getParcelableExtra("session");
		if (mSessionItem == null) {
			if (mUserInfo != null && mContact != null) {
				mSessionItem = new TSession(mUserInfo.getJid(),
						mContact.getJID());
				mSessionItem
						.setTime(String.valueOf(System.currentTimeMillis()));
			}
		}
		SessionTable table = SessionTable.getInstance();
		table.write(mSessionItem);
	}

	private void setup() {
		mBtnStrangeToContact = (Button) findViewById(R.id.chat_addstranger_to_mycontactBtn);
		mBtnStrangeToContact.setOnClickListener(this);

		mStrangeToContact = (TextView) findViewById(R.id.chat_addstranger_to_mycontact_text);

		mConverList = (ListView) findViewById(R.id.chat_conversation_list);
		mConverList.setOnItemClickListener(this);
		//

		// mConverList.setAdapter(mAdapter);
		// mConverList.setStackFromBottom(true);

		mFaceLayout = (LinearLayout) findViewById(R.id.chat_conversation_face_view);

		mFaceGridView = (GridView) findViewById(R.id.chat_conversation_face_gridview);
		mFaceGridView.setOnItemClickListener(this);
		mFaceGridView.setAdapter(faceAdapter());

		mBtnFace = (ImageView) findViewById(R.id.chat_conversation_faceBtn);
		mBtnFace.setOnClickListener(this);

		mInput = (EditText) findViewById(R.id.chat_conversation_input);
		mInput.setOnClickListener(this);

		mBtnSend = (Button) findViewById(R.id.chat_conversation_sendBtn);
		mBtnSend.setOnClickListener(this);

		mBtnImage = (LinearLayout) findViewById(R.id.chat_conversation_imageBtn);
		mBtnImage.setOnClickListener(this);

		mBtnAudio = (LinearLayout) findViewById(R.id.chat_conversation_audioBtn);
		mBtnAudio.setOnClickListener(this);
		mBtnAudio.setOnTouchListener(this);

		mBtnVideo = (LinearLayout) findViewById(R.id.chat_conversation_videoBtn);
		mBtnVideo.setOnClickListener(this);
	}

	/**
	 * 表情适配器
	 * 
	 * @return
	 */
	private SimpleAdapter faceAdapter() {
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		// 生成107个表情的id，封装
		for (int i = 0; i < 107; i++) {
			try {
				if (i < 10) {
					Field field = R.drawable.class.getDeclaredField("f00" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else if (i < 100) {
					Field field = R.drawable.class.getDeclaredField("f0" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else {
					Field field = R.drawable.class.getDeclaredField("f" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			Map<String, Object> listItem = new HashMap<String, Object>();
			listItem.put("image", imageIds[i]);
			listItems.add(listItem);
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
				R.layout.chat_conversation_face_gridview_item,
				new String[] { "image" },
				new int[] { R.id.chat_conversation_face_gridview_image });

		return simpleAdapter;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	private void sendChatMessage(String msg){
		if(StringHelper.isText(msg)){
			if(mTChat!=null){
				Message oMo = new Message();
				oMo.setBody(msg);
				oMo.setTo(mContact.getJID());
				oMo.setFrom(mUserInfo.getJid());
				boolean send = mTChat.sendMessage(new TMessage(oMo));
				if(send){
					mCursor.requery();
					messageAdapter.notifyDataSetChanged();
					mInput.setText("");
				}else{
					
				}
			}
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.chat_conversation_msg_photo:
		// Contact contact = (Contact) v.getTag();
		// toContactDetailAty(contact);
		// break;
		case R.id.chat_conversation_faceBtn:
			ChatHideInput.hideInput(this);
			showFaceView();
			break;

		case R.id.chat_conversation_input:
			hideFaceView();
			break;

		case R.id.chat_conversation_sendBtn:
			ChatHideInput.hideInput(this);
			sendChatMessage(mInput.getText().toString());
			break;

		case R.id.chat_conversation_imageBtn:
			ChatHideInput.hideInput(this);
			// sendChatImageMessage();

			break;

		case R.id.chat_conversation_audioBtn: // 录音

			break;

		case R.id.chat_conversation_videoBtn:
			ChatHideInput.hideInput(this);
			// RecorderManager.startVideoRecording(this);
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (parent == mFaceGridView) { // 表情
			Bitmap bitmap = null;
			bitmap = BitmapFactory.decodeResource(getResources(),
					imageIds[position % imageIds.length]);
			ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);
			String str = null;
			if (position < 10) {
				str = "f00" + position;
			} else if (position < 100) {
				str = "f0" + position;
			} else {
				str = "f" + position;
			}
			SpannableString spannableString = new SpannableString(str);
			spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			mInput.append(spannableString);
			mFaceLayout.setVisibility(View.GONE);
		}
	}

	/**
	 * 表情选择对话框
	 */
	private void showFaceView() {
		mFaceLayout.setVisibility(View.VISIBLE);
	}
	/**
	 * 隐藏表情布局
	 */
	private void hideFaceView() {
		mFaceLayout.setVisibility(View.GONE);
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}
	android.os.Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mCursor.requery();
			messageAdapter.notifyDataSetChanged();
		}
	};

	@Override
	public void onChageTable(boolean isChage, AbstractTable AbsTable) {
		if(isChage){
			if(AbsTable instanceof MessageTable){
				//更新数据
				handler.sendEmptyMessage(0);
			}
		}
	}

}
